const app = getApp()
import { getProjectSpaceCategory, addProjectSpace, deleteProjectSpace, updateProjectSpace } from '../../../../api/index'

Page({
  data: {
    projectId: '',
    safeBottom: 0,
    list: [],
    basicInfo: {},
    showInfoModal: false
  },
  async deleteSpace ({ currentTarget: { dataset: { item } } }) {
    try {
      const { confirm } = await wx.$pro.showModal({ title: '提示', content: '确定要删除该空间吗？' })
      if (confirm) {
        await deleteProjectSpace({ projectId: this.data.projectId, spaceId: item.spaceId })
        wx.showToast({ title: '删除成功！', icon: 'none' })
        this.getList()
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  editSpace ({ currentTarget: { dataset: { item } } }) {
    this.data.basicInfo = {
      title: '编辑空间',
      value: item.spaceName,
      key: 'spaceNewName',
      spaceId: item.spaceId,
      placeholder: '请输入空间名称'
    }
    this.setData({ showInfoModal: true, basicInfo: this.data.basicInfo })
  },
  addSpace () {
    this.data.basicInfo = {
      title: '添加空间',
      value: '',
      key: 'spaceName',
      placeholder: '请输入空间名称'
    }
    this.setData({ showInfoModal: true, basicInfo: this.data.basicInfo })
  },
  closeInfoPop () {
    this.setData({ showInfoModal: false })
  },
  async changeInfo ({ detail }) {
    try {
      let query = {
        projectId: this.data.projectId
      }
      query[detail.key] = detail.value
      if (detail.spaceId) {
        query.spaceId = detail.spaceId
        await updateProjectSpace({ ...query })
      } else {
        await addProjectSpace({ ...query })
      }
      this.closeInfoPop()
      wx.showToast({ title: query.spaceId ? '编辑成功！' : '添加成功！', icon: 'none' })
      this.getList()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getList () {
    try {
      const { ResultSet } = await getProjectSpaceCategory({ projectId: this.data.projectId })
      this.setData({ list: ResultSet.userData.projectSpace })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ id }) {
    const { screenHeight, safeArea: { bottom } } = wx.$pro.getSystemInfoSync()
    this.setData({ safeBottom: screenHeight - bottom, projectId: id })
    this.getList()
  }
})